package com.controller.system;

import com.common.anntation.Log;
import com.common.emums.BusinessType;
import com.common.excel.ExcelUtil;
import com.common.utils.EntityConversionUtil;
import com.common.utils.StringUtils;
import com.github.pagehelper.PageInfo;
import com.model.base.PageResult;
import com.model.base.Result;
import com.model.domain.device.GetDeviceObdBaseInfoDO;
import com.model.domain.device.GetDevicePcbBaseInfoDO;
import com.model.domain.device.GetDevicePmdBaseInfoDO;
import com.model.domain.system.GetSystemTestDeviceInfoDO;
import com.model.dto.system.testDevice.GetTestDeviceListDTO;
import com.model.dto.system.testDevice.SaveTestDeviceInfoDTO;
import com.model.dto.system.testDevice.UpdateDomainInfoDTO;
import com.model.pojo.device.DeviceObdBaseInfo;
import com.model.pojo.device.DevicePcbBaseInfo;
import com.model.pojo.device.DevicePmdBaseInfo;
import com.model.pojo.system.SystemTestDeviceInfo;
import com.model.vo.system.testDevice.getTestDeviceList.GetTestDeviceListVO;
import com.service.device.DeviceObdBaseInfoService;
import com.service.device.DevicePcbBaseInfoService;
import com.service.device.DevicePmdBaseInfoService;
import com.service.system.SystemTestDeviceInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * TODO
 *
 * @Description
 * @Author tm
 * @Date 2023-12-15 23:07
 **/
@Api(tags = {"测试设备管理"})
@Slf4j
@RestController
@RequestMapping("/v1/system/testDevice")
@RequiredArgsConstructor
public class SystemTestDeviceInfoController {
    private final SystemTestDeviceInfoService systemTestDeviceInfoService;
    private final DeviceObdBaseInfoService deviceObdBaseInfoService;
    private final DevicePcbBaseInfoService devicePcbBaseInfoService;
    private final DevicePmdBaseInfoService devicePmdBaseInfoService;
    @Log(title = "测试设备管理-设备列表", businessType = BusinessType.SELECT)
    @ApiOperation(value = "设备列表")
    @PostMapping("/getTestDeviceList")
    public Result<PageResult<List<GetTestDeviceListVO>>> getTestDeviceList(@RequestBody @Valid GetTestDeviceListDTO dto){
        List<GetTestDeviceListVO> voList = new ArrayList<GetTestDeviceListVO>();
        GetSystemTestDeviceInfoDO getSystemTestDeviceInfoDO = EntityConversionUtil.copy(dto,GetSystemTestDeviceInfoDO.class);
        if(dto.getType()!=null && !"".equals(dto.getType())){
            getSystemTestDeviceInfoDO.setType(Integer.parseInt(dto.getType()));
        }
        getSystemTestDeviceInfoDO.setSortRow("createTime");
        List<SystemTestDeviceInfo> list = systemTestDeviceInfoService.getPageList(getSystemTestDeviceInfoDO);
        if(list!=null && list.size()>0){
            list.forEach(item->{
                GetTestDeviceListVO vo = EntityConversionUtil.copy(item,GetTestDeviceListVO.class);
                if(item.getType() == 1) {
                    DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getById(item.getDeviceId());
                    if (baseInfo.getDomainId() != null) {
                        if (baseInfo.getDomainId() == 4) {
                            vo.setDataUrl(1);
                        } else if (baseInfo.getDomainId() == 5) {
                            vo.setDataUrl(2);
                        }
                    }
                }else if(item.getType() == 2){
                    DevicePcbBaseInfo baseInfo = devicePcbBaseInfoService.getById(item.getDeviceId());
                    if (baseInfo.getDomainId() != null) {
                        if (baseInfo.getDomainId() == 10) {
                            vo.setDataUrl(1);
                        } else if (baseInfo.getDomainId() == 11) {
                            vo.setDataUrl(2);
                        }
                    }
                }else if(item.getType() == 3){
                    DevicePmdBaseInfo baseInfo = devicePmdBaseInfoService.getById(item.getDeviceId());
                    if (baseInfo.getDomainId() != null) {
                        if (baseInfo.getDomainId() == 7) {
                            vo.setDataUrl(1);
                        } else if (baseInfo.getDomainId() == 12) {
                            vo.setDataUrl(2);
                        }
                    }
                }
                voList.add(vo);
            });
//            voList = EntityConversionUtil.copyList(list,GetTestDeviceListVO.class);
        }
        PageInfo<SystemTestDeviceInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<GetTestDeviceListVO>> build = PageResult.<List<GetTestDeviceListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "测试设备管理-保存设备信息", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "保存设备信息")
    @PostMapping("/saveTestDeviceInfo")
    public Result<Objects> saveTestDeviceInfo(@RequestBody @Valid SaveTestDeviceInfoDTO dto){
        Long id = 0l;
        Long oldDomainId = null;
        if(StringUtils.isNotBlank(dto.getDtu())) {
            SystemTestDeviceInfo info = systemTestDeviceInfoService.getByDtu(dto.getDtu(), dto.getType());
            if (info != null) {
                return Result.fail("9999", "该设备已保存");
            }
            if(dto.getType() == 1) {//OBD
                DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(dto.getDtu());
                if (baseInfo == null) {
                    return Result.fail("9999", "该设备不存在");
                }
                id = baseInfo.getId();
                oldDomainId = baseInfo.getDomainId();
                baseInfo.setDomainId(4l);
                deviceObdBaseInfoService.update(baseInfo);
            }else if(dto.getType() == 2){//安卓版
                DevicePcbBaseInfo baseInfo = devicePcbBaseInfoService.getByDtu(dto.getDtu());
                if (baseInfo == null) {
                    return Result.fail("9999", "该设备不存在");
                }
                id = baseInfo.getId();
                oldDomainId = baseInfo.getDomainId();
                baseInfo.setDomainId(10l);
                devicePcbBaseInfoService.update(baseInfo);
            }else if(dto.getType() == 3){//播种机
                DevicePmdBaseInfo baseInfo = devicePmdBaseInfoService.getByDtu(dto.getDtu());
                if (baseInfo == null) {
                    return Result.fail("9999", "该设备不存在");
                }
                id = baseInfo.getId();
                oldDomainId = baseInfo.getDomainId();
                baseInfo.setDomainId(7l);
                devicePmdBaseInfoService.update(baseInfo);
            }
            SystemTestDeviceInfo testDeviceInfo = new SystemTestDeviceInfo();
            testDeviceInfo.setDtu(dto.getDtu());
            testDeviceInfo.setDeviceId(id);
            testDeviceInfo.setRemark(dto.getRemark());
            testDeviceInfo.setType(dto.getType());
            testDeviceInfo.setOldDomainId(oldDomainId);
            testDeviceInfo.setFileUrl(dto.getFileUrl());
            int num = systemTestDeviceInfoService.save(testDeviceInfo);
        }
        if(StringUtils.isNotBlank(dto.getFileUrl())){
            List<List<Object>> list = new ArrayList<>();
            try{
                String filePath1 = "";
                if (StringUtils.isNotBlank(dto.getFileUrl()) && dto.getFileUrl().indexOf("upload") > -1) {
                    int index = dto.getFileUrl().indexOf("upload");
                    filePath1 = "/zhnl/ftp/" + dto.getFileUrl().substring(index, dto.getFileUrl().length());
                }

                File file1 = new File(filePath1);
                String fileName1 = filePath1.split("\\/")[filePath1.split("\\/").length-1];
                FileInputStream in1 =new FileInputStream(file1);
                list = ExcelUtil.getBankListByExcel(in1,fileName1);
            }catch (Exception e){
                e.printStackTrace();
            }
            if(!CollectionUtils.isEmpty(list)){
                List<String> dtuList = new ArrayList<>();
                for (int i=0;i<list.size();i++) {
                    List<Object> oList = list.get(i);
                    dtuList.add(oList.get(0).toString());
                }
                if(dto.getType() == 1){//obd
                    long domainId = 4l;
                    GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
                    getDeviceObdBaseInfoDO.setDtus(dtuList);
                    getDeviceObdBaseInfoDO.setSortRow("id");
                    List<DeviceObdBaseInfo> updateBaseList = new ArrayList<>();
                    List<SystemTestDeviceInfo> testDeviceList = new ArrayList<>();
                    List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
                    if(baseList.size()>0){
                        for(DeviceObdBaseInfo baseInfo:baseList){
                            SystemTestDeviceInfo testDeviceInfo = new SystemTestDeviceInfo();
                            testDeviceInfo.setRemark(dto.getRemark());
                            testDeviceInfo.setDtu(baseInfo.getDtu());
                            testDeviceInfo.setDeviceId(baseInfo.getId());
                            testDeviceInfo.setCreateTime(new Date());
                            testDeviceInfo.setType(dto.getType());
                            testDeviceInfo.setOldDomainId(baseInfo.getDomainId());
                            testDeviceList.add(testDeviceInfo);
                            baseInfo.setDomainId(domainId);
                            updateBaseList.add(baseInfo);
                        }
                    }
                    if(updateBaseList.size()>0){
                        systemTestDeviceInfoService.saveList(testDeviceList);
                        deviceObdBaseInfoService.updateList(updateBaseList);
                    }
                }else if(dto.getType() == 2){
                    long domainId = 10l;
                    GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = new GetDevicePcbBaseInfoDO();
                    getDevicePcbBaseInfoDO.setDtus(dtuList);
                    getDevicePcbBaseInfoDO.setSortRow("id");
                    List<DevicePcbBaseInfo> updateBaseList = new ArrayList<>();
                    List<SystemTestDeviceInfo> testDeviceList = new ArrayList<>();
                    List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
                    if(baseList.size()>0){
                        for(DevicePcbBaseInfo baseInfo:baseList){
                            SystemTestDeviceInfo testDeviceInfo = new SystemTestDeviceInfo();
                            testDeviceInfo.setRemark(dto.getRemark());
                            testDeviceInfo.setDtu(baseInfo.getDtu());
                            testDeviceInfo.setDeviceId(baseInfo.getId());
                            testDeviceInfo.setCreateTime(new Date());
                            testDeviceInfo.setType(dto.getType());
                            testDeviceInfo.setOldDomainId(baseInfo.getDomainId());
                            testDeviceList.add(testDeviceInfo);
                            baseInfo.setDomainId(domainId);
                            updateBaseList.add(baseInfo);
                        }
                    }
                    if(updateBaseList.size()>0){
                        devicePcbBaseInfoService.updateList(updateBaseList);
                        systemTestDeviceInfoService.saveList(testDeviceList);
                    }
                }
                else if(dto.getType() == 3) {
                    long domainId =7l;
                    GetDevicePmdBaseInfoDO getDevicePmdBaseInfoDO = new GetDevicePmdBaseInfoDO();
                    getDevicePmdBaseInfoDO.setDtus(dtuList);
                    getDevicePmdBaseInfoDO.setSortRow("id");
                    List<DevicePmdBaseInfo> updateBaseList = new ArrayList<>();
                    List<SystemTestDeviceInfo> testDeviceList = new ArrayList<>();
                    List<DevicePmdBaseInfo> baseList = devicePmdBaseInfoService.getAllList(getDevicePmdBaseInfoDO);
                    if(baseList.size()>0){
                        for(DevicePmdBaseInfo baseInfo:baseList){
                            SystemTestDeviceInfo testDeviceInfo = new SystemTestDeviceInfo();
                            testDeviceInfo.setRemark(dto.getRemark());
                            testDeviceInfo.setDtu(baseInfo.getDtu());
                            testDeviceInfo.setDeviceId(baseInfo.getId());
                            testDeviceInfo.setCreateTime(new Date());
                            testDeviceInfo.setType(dto.getType());
                            testDeviceInfo.setOldDomainId(baseInfo.getDomainId());
                            testDeviceList.add(testDeviceInfo);
                            baseInfo.setDomainId(domainId);
                            updateBaseList.add(baseInfo);
                        }
                    }
                    if(updateBaseList.size()>0){
                        devicePmdBaseInfoService.updateList(updateBaseList);
                        systemTestDeviceInfoService.saveList(testDeviceList);
                    }
                }
            }
        }
        return Result.suc();
    }

    @Log(title = "测试设备管理-修改数据地址", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改数据地址")
    @PostMapping("/updateDomainInfo")
    public Result<Objects> updateDomainInfo(@RequestBody @Valid UpdateDomainInfoDTO dto){
        SystemTestDeviceInfo info = systemTestDeviceInfoService.getById(dto.getId());
        if(info == null){
            return Result.fail("9999","该记录不存在");
        }

        List<String> dtuList = new ArrayList<>();
        /*if(StringUtils.isNotBlank(info.getFileUrl())) {
            List<List<Object>> list = new ArrayList<>();
            try {
                String filePath1 = "";
                if (StringUtils.isNotBlank(info.getFileUrl()) && info.getFileUrl().indexOf("upload") > -1) {
                    int index = info.getFileUrl().indexOf("upload");
                    filePath1 = "/zhnl/ftp/" + info.getFileUrl().substring(index, info.getFileUrl().length());
                }

                File file1 = new File(filePath1);
                String fileName1 = filePath1.split("\\/")[filePath1.split("\\/").length - 1];
                FileInputStream in1 = new FileInputStream(file1);
                list = ExcelUtil.getBankListByExcel(in1, fileName1);

                if(list.size()>0){
                    for (int i=1;i<list.size();i++) {
                        List<Object> oList = list.get(i);
                        dtuList.add(oList.get(0).toString());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/
        if(info.getType() == 1){//OBD设备
            int num = 0;
            long domainId = 0;
            if(dto.getType() == 1){//生产
                domainId = 1;
            }else if(dto.getType() == 2){//测试
                domainId = 4;
            }else if(dto.getType() == 3){//维修
                domainId = 5;
            }
            if(StringUtils.isNotBlank(info.getDtu())) {
                DeviceObdBaseInfo baseInfo = deviceObdBaseInfoService.getByDtu(info.getDtu());
                if (baseInfo == null) {
                    return Result.fail("9999", "设备不存在");
                }
                baseInfo.setDomainId(domainId);
                num = deviceObdBaseInfoService.update(baseInfo);
            }
            if(dtuList.size()>0){
                GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
                getDeviceObdBaseInfoDO.setDtus(dtuList);
                getDeviceObdBaseInfoDO.setSortRow("id");
                List<DeviceObdBaseInfo> updateBaseList = new ArrayList<>();
                List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
                if(baseList.size()>0){
                    for(DeviceObdBaseInfo baseInfo:baseList){
                        baseInfo.setDomainId(domainId);
                        updateBaseList.add(baseInfo);
                    }
                }
                if(updateBaseList.size()>0){
                    deviceObdBaseInfoService.updateList(updateBaseList);
                }
                num = 1;
            }
            if(num>0){
                systemTestDeviceInfoService.deleteById(dto.getId());
            }
        }else if(info.getType() == 2){//安卓版
            long domainId = 0;
            if(dto.getType() == 1){//生产
                domainId = 8;
            }else if(dto.getType() == 2){//测试
                domainId = 10;
            }else if(dto.getType() == 3){//维修
                domainId = 11;
            }

            DevicePcbBaseInfo baseInfo = devicePcbBaseInfoService.getById(info.getDeviceId());
            if(baseInfo == null){
                return Result.fail("9999","设备不存在");
            }

            baseInfo.setDomainId(domainId);
            int num = devicePcbBaseInfoService.update(baseInfo);
            if(num>0 && dto.getType() == 1){
                systemTestDeviceInfoService.deleteById(dto.getId());
            }
        }else if(info.getType() == 3){//播种
            long domainId = 0;
            if(dto.getType() == 1){//生产
                domainId = 6;
            }else if(dto.getType() == 2){//测试
                domainId = 7;
            }else if(dto.getType() == 3){//维修
                domainId = 12;
            }

            DevicePmdBaseInfo baseInfo = devicePmdBaseInfoService.getById(info.getDeviceId());
            if(baseInfo == null){
                return Result.fail("9999","设备不存在");
            }

            baseInfo.setDomainId(domainId);
            int num = devicePmdBaseInfoService.update(baseInfo);
            if(num>0 && dto.getType() == 1){
                systemTestDeviceInfoService.deleteById(dto.getId());
            }
        }
        return Result.suc();
    }
}
